/*
 * @lc app=leetcode.cn id=43 lang=typescript
 *
 * [43] 字符串相乘
 */

// @lc code=start
function multiply(num1: string, num2: string): string {
  const m = num1.length;
  const n = num2.length;
  const a = new Array(m).fill(0);
  const b = new Array(n).fill(0);
  const c = new Array(m + n - 1).fill(0);

  for (let i = 0; i < m; i++) {
    a[m - 1 - i] = Number(num1[i]);
  }
  for (let i = 0; i < n; i++) {
    b[n - 1 - i] = Number(num2[i]);
  }

  // 处理相乘
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      c[i + j] += a[i] * b[j];
    }
  }

  // 处理进位
  for (let i = 0; i < c.length; i++) {
    if (c[i] < 10) continue;
    // 防止高位需要进位
    if (i === c.length - 1) c.push(0);
    c[i + 1] += (c[i] / 10) >> 0;
    c[i] = c[i] % 10;
  }

  // 处理前导零
  while (c.length > 1 && c[c.length - 1] === 0) c.pop();

  // 更新结果
  let ans = '';
  for (let i = c.length - 1; i >= 0; i--) {
    ans += String(c[i]);
  }

  return ans;
}
// @lc code=end
